import { useDispatch, useSelector } from "react-redux"
import { MyHead } from "../../../components/head"
import { useTiaoZhuan } from "../../../hooks/routers"
import '../../../styles/homes/my.scss'
import { Avatar, List, Mask, ProgressBar, Toast, Button, } from "antd-mobile"
import { useEffect, useState ,useRef} from 'react'
import { changeShuLiang, changeUserData, getUserInfo } from "../../../rtk/reduers/data"
import { StarOutline, HeartOutline, DeleteOutline, SetOutline, HistogramOutline, FillinOutline, LockOutline, UnorderedListOutline, PayCircleOutline, AppstoreOutline, ChatAddOutline } from 'antd-mobile-icons'
import { useInterval, useLocalStorageState } from "ahooks"
import { AppDispatch, RootReducer, dataTypes } from "../../../types/store"
import { changeImg, changeUserInfo } from "../../../api/user"
import { getPing, userCol, userLikes } from "../../../api/AddMs"
import { rootReducer } from "../../../rtk/store/store"



const MyWd = () => {
    const { Tz } = useTiaoZhuan()
    const [tokenData, setToken] = useLocalStorageState<string | undefined>('token')
    // useselector接收两个类型 第一个是state的类型 第二个是结果的类型
    const userData = useSelector<RootReducer, foundUserType | null>((state) => state.MyData.userData)
    const datas =  useSelector<RootReducer,dataTypes>(s=>s.MyData)
    const [show, setshow] = useState(false);
    const [randoms, setrandom] = useState(Math.floor(Math.random() * 1000))
    const [num, setnum] = useState(0)
    const [times, settimes] = useState(0)

    const clear = useInterval(() => {
        if (num < 100) {
            setnum(num + 1)

        } else {
            setshow(false)
            setrandom(0)
            Toast.show({
                content: "清除缓存成功"
            })
            clear()
        }
    }, times)
    // 使用泛型来定义 Dispatch 类型，使它能够接受异步 Thunk action，使用泛型来定义 Dispatch 类型，使它能够接受异步 Thunk action
    const chufa = ()=>{
        fileRef.current!.click()
    }
    const dispatch: AppDispatch = useDispatch();
    useEffect(() => {
        clear();
        dispatch(getUserInfo());
    }, [])

    const logoutAction = () => {                       
        setToken('')
        dispatch(changeUserData({}))
    }

    const obj = [
        {
            title: '我的收藏',
            icon: <StarOutline />,
            path: '/myXQ/1',
            dis: true,
            extra:datas.collect
        },
        {
            title: '我的点赞',
            icon: <HeartOutline />,
            path: '/myXQ/2',
            dis: true,
            extra:datas.likes
        },
        {
            title: '我的评论',
            icon: <HistogramOutline />,
            path: '/mypings',
            dis: true,
            extra:datas.pings
        },
        {
            title: '我的面试',
            icon: <FillinOutline />,
            path: '/wdms',
            dis: true,

        },
        {
            title: '修改密码',
            icon: <LockOutline />,
            path: '/setpass',
            dis: true,

        },
        {
            title: '账单',
            icon: <UnorderedListOutline />,
            path: '',
            dis: true,

        },
        {
            title: '总资产',
            icon: <PayCircleOutline />,
            path: '',
            dis: true,

        },
        {
            title: '公告',
            icon: <AppstoreOutline />,
            path: ''
        },
        {
            title: '清除缓存',
            icon: <DeleteOutline />,
            path: '',
            exra: `${randoms}M`,
            callback: () => {
                console.log(num);

                if (num >= 99) {
                    Toast.show({
                        content: "缓存已经清除"
                    })
                } else {
                    setshow(true)

                    settimes(50)

                }
            }
        },
        {
            title: '联系我们',
            icon: <ChatAddOutline />,
            path: ''
        },
        {
            title: '设置',
            icon: <SetOutline />,
            path: ''

        },

    ]
    const fileRef = useRef<HTMLInputElement>(null);
    const updateFiles = async()=>{
        console.log(fileRef.current?.files);
        const data = new FormData();
        data.append('file',fileRef.current!.files![0])
        let res = await changeImg(data);
        if(res.code == 200){
            let res2 = await changeUserInfo({...userData!,avatar:res.path})
            if(res2.code == 200){
                dispatch(changeUserData({...userData,avatar:res.path}))
                console.log(userData);
                
            }
        }
    }
    const getlikesNum = async()=>{

        let res = await userLikes(userData!.phone)
        let res2  =await  userCol(userData!.phone)
        let res3  = await getPing(userData!.phone)
        console.log(res,res2,res3);
        dispatch(changeShuLiang({pings:res3.result.length,likes:res.result.length,collect:res2.result.length}))
    }
    useEffect(()=>{
        userData && getlikesNum()
    },[])
    return (
        <div className="myWd" >
            {show && <Mask
                visible={show}
                onMaskClick={() => setshow(false)}
                opacity='thin'>
                <div style={{ width: "100%", height: '100%', position: "relative", padding: 10, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>

                    <ProgressBar percent={num} style={{ width: '100%' }} />

                </div>
            </Mask>
            }
            <MyHead title='我的' noBack={false} />
            <div className="titles">
                <Avatar onClick={userData? chufa : ()=>Tz('/login')}  src={ userData?.avatar?.replace('public','http://192.168.57.160:3333') || "http://101.37.23.156/wh2217/myapp/assets/photo-2002f819.png"} style={{ "--size": '70px' }} />
                <input type="file" ref={fileRef} onChange={updateFiles} style={{display:"none"}}/>
                <div>{userData?.username}</div>
                <div>{userData?.phone}</div>
            </div>
            <List header='操作列表'>
                {
                    obj.map((item, index) => (
                        item.dis ? (userData &&
                            <List.Item extra={item.extra} key={index} prefix={item.icon} onClick={() => Tz(item.path)}>{item.title}</List.Item>)
                            :
                            <List.Item extra={item.extra} key={index} prefix={item.icon} onClick={() => item.callback ? item.callback() : Tz(item.path)}>{item.title}</List.Item>

                    ))
                }
            </List>
            {userData && <div style={{ margin: 16, }}>
                <Button block color="default" onClick={logoutAction}> 注销登录 </Button>
            </div>}
        </div>
    )
}

export default MyWd